import React from 'react';
import type {FormInstance} from 'antd';
import type {FormItemConfig} from '@/types/form';
import {isArray, isString, isUnDef} from '@/utils/is.ts';

type EventHandlers = {
    [key: string]: (options: { value: any; item: any, form?: FormInstance }) => void;
};

type ComponentProps = {
    item: FormItemConfig;
    form: FormInstance;
    initialValues: Record<string, any>;
    handlers?: EventHandlers;
    style?: Record<any, any>;
    slots?: Record<string, (value: any) => void>;
};


// 声明组件数组
const SelectTypes = [
    'Select',
    'RemoteSelect',
    'TreeSelect',
    'TimePicker',
    'DatePicker',
    'DateRangePicker',
    'DateTimePicker',
    'DateMonthPicker',
    'DateYearPicker',
    'DateWeekPicker',
    'TimeRangePicker',
    'TimeSelect',  // 只有一个 TimeSelect
    'SelectV2'
];

const setFormIsShow = (item: FormItemConfig, initialValues: any) => {
    if (!item.screen) return true;
    if (isUnDef(initialValues[item.screen.key])) return false;
    return isArray(item.screen.value)
        ? item.screen.value.includes(initialValues[item.screen.key])
        : isArray(initialValues[item.screen.key])
            ? initialValues[item.screen.key].includes(item.screen.value)
            : isString(initialValues[item.screen.key]) &&
            initialValues[item.screen.key].includes(',')
                ? initialValues[item.screen.key]
                    .split(',')
                    .includes(item.screen.value)
                : item.screen.value === initialValues[item.screen.key];
};

const setPropsSlots = (
    item: FormItemConfig,
    props: any,
    slots: Record<string, any>,
) => {
    const keys = Object.keys(slots).filter((key: string) =>
        key.includes(item.field),
    );
    const itemSlots = item.slots ? Object.keys(item.slots) : [];
    keys.forEach((key: string) => {
        const str = key.split('-')[1];
        props[str] = slots[key];
    });
    itemSlots.forEach((slot: string) => {
        props[slot] = item.slots[slot];
    });
};

const getTextPlaceholder = (item: FormItemConfig) => {
    const textMap = ['Input', 'Autocomplete', 'InputNumber', 'InputPassword'];
    if (textMap.includes(item.component)) {
        return {
            placeholder: `请输入${item.label
                ?.replace('：', '')
                .replace(':', '')
                .replace(/[0-9]、/g, '')}`,
        };
    }
    if (SelectTypes.includes(item.component)) {
        // 一些范围选择器
        const twoTextMap = [
            'datetimerange',
            'daterange',
            'monthrange',
            'datetimerange',
            'daterange',
        ];
        if (
            item.component.includes("Range")
        ) {
            // return {
            //     startPlaceholder: '开始时间',
            //     endPlaceholder: '结束时间',
            //     rangeSeparator: '-',
            // };
        } else {
            return {
                placeholder: `请选择${item.label?.replace('：', '')}`,
            };
        }
    }
    return {};
};

const getComponentProps = ({
                               item,
                               form,
                               handlers,
                               initialValues,
                               style,
                               slots,
                           }: ComponentProps) => {
    const comStyle = {
        width: '100%',
        ...style,
    };
    const placeholderList = getTextPlaceholder(item);
    const props: any = {
        ...item.componentProps,
        ...(item.options && {options: item.options}),
        style: comStyle,
        ...placeholderList,
    };
    if (initialValues[item.field]) {
        props['value'] = initialValues[item.field];
    }
    // 插槽处理
    if (slots) {
        setPropsSlots(item, props, slots);
    }
    if (props.inputType) {
        delete props.inputType;
    }
    // 回调事件处理
    Object.entries(props).forEach(([propName, methodKey]) => {
        if (
            typeof methodKey === 'string' &&
            propName.includes('on') &&
            handlers?.[methodKey]
        ) {
            switch (item.component) {
                case 'Input':
                case 'RadioGroup':
                    props[propName] = (
                        e: React.ChangeEvent<HTMLInputElement>,
                    ) => {
                        handlers?.[methodKey]?.({
                            value: e.target.value,
                            form,
                            item
                        });
                    };
                    break;
                default:
                    props[propName] = (value: any) => {
                        handlers?.[methodKey]?.({
                            value, form, item
                        });
                    };
                    break;
            }
        }
    });
    return props;
};

const getRealValue = (item: any, value: any) => {
    if (!SelectTypes.includes(item.component)) return value;
    const options = item.componentProps.options;
    const result = options.find((zle: any) => zle.value === value);
    return result ? result.label : "--"
}

export {setFormIsShow, getTextPlaceholder, setPropsSlots, getComponentProps, getRealValue};
